﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 生产报工服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class productionreportService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<productionreport> _productionreportRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public productionreportService(SqlSugarRepository<productionreport> productionreportRep, ISqlSugarClient sqlSugarClient)
    {
        _productionreportRep = productionreportRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询生产报工 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询生产报工")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<productionreportOutput>> Page(PageproductionreportInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _productionreportRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.reportnumber.Contains(input.Keyword) || u.workordernumber.Contains(input.Keyword) || u.productionpersonnel.Contains(input.Keyword) || u.attachments.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.reportnumber), u => u.reportnumber.Contains(input.reportnumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.workordernumber), u => u.workordernumber.Contains(input.workordernumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.productionpersonnel), u => u.productionpersonnel.Contains(input.productionpersonnel.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.attachments), u => u.attachments.Contains(input.attachments.Trim()))
            .WhereIF(input.reporttimeRange?.Length == 2, u => u.reporttime >= input.reporttimeRange[0] && u.reporttime <= input.reporttimeRange[1])
            .WhereIF(input.procedurecode != null, u => u.procedurecode == input.procedurecode)
            .WhereIF(input.processname != null, u => u.processname == input.processname)
            .WhereIF(input.productcode != null, u => u.productcode == input.productcode)
            .WhereIF(input.productname != null, u => u.productname == input.productname)
            .WhereIF(input.productspecification != null, u => u.productspecification == input.productspecification)
            .WhereIF(input.productiontimeRange?.Length == 2, u => u.productiontime >= input.productiontimeRange[0] && u.productiontime <= input.productiontimeRange[1])
            .WhereIF(input.quantityreported != null, u => u.quantityreported == input.quantityreported)
            .WhereIF(input.qualifiedquantity != null, u => u.qualifiedquantity == input.qualifiedquantity)
            .WhereIF(input.unqualifiedquantity != null, u => u.unqualifiedquantity == input.unqualifiedquantity)
            .LeftJoin<Processmanage>((u, procedurecode) => u.procedurecode == procedurecode.Id)
            .LeftJoin<Processmanage>((u, procedurecode, processname) => u.processname == processname.Id)
            .LeftJoin<Partnum>((u, procedurecode, processname, productcode) => u.productcode == productcode.Id)
            .LeftJoin<Partnum>((u, procedurecode, processname, productcode, productname) => u.productname == productname.Id)
            .LeftJoin<Partnum>((u, procedurecode, processname, productcode, productname, productspecification) => u.productspecification == productspecification.Id)
            .Select((u, procedurecode, processname, productcode, productname, productspecification) => new productionreportOutput
            {
                Id = u.Id,
                reportnumber = u.reportnumber,
                reporttime = u.reporttime,
                workordernumber = u.workordernumber,
                procedurecode = u.procedurecode,
                procedurecodeFkDisplayName = $"{procedurecode.encoding}",
                processname = u.processname,
                processnameFkDisplayName = $"{processname.processname}",
                productcode = u.productcode,
                productcodeFkDisplayName = $"{productcode.PartNumCoding}",
                productname = u.productname,
                productnameFkDisplayName = $"{productname.PartNumName}",
                productspecification = u.productspecification,
                productspecificationFkDisplayName = $"{productspecification.SpeciFicationNumber}",
                productionpersonnel = u.productionpersonnel,
                productiontime = u.productiontime,
                quantityreported = u.quantityreported,
                qualifiedquantity = u.qualifiedquantity,
                unqualifiedquantity = u.unqualifiedquantity,
                attachments = u.attachments,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取生产报工详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取生产报工详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<productionreport> Detail([FromQuery] QueryByIdproductionreportInput input)
    {
        return await _productionreportRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加生产报工 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加生产报工")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddproductionreportInput input)
    {
        var entity = input.Adapt<productionreport>();
       entity.reportnumber = "MS" + DateTime.Now.ToString("yyyyMMddHHmmss");
        entity.reporttime = DateTime.Now;
        entity.productionpersonnel = entity.CreateUserName;
         entity.productiontime = DateTime.Now;
        return await _productionreportRep.InsertAsync(entity) ? entity.Id : 0;
    } 

    /// <summary>
    /// 更新生产报工 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新生产报工")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateproductionreportInput input)
    {
        var entity = input.Adapt<productionreport>();
        await _productionreportRep.AsUpdateable(entity)
        .IgnoreColumns(u => new {
            u.reportnumber,
            u.reporttime,
            u.productionpersonnel,
            u.productiontime,
        })
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除生产报工 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除生产报工")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteproductionreportInput input)
    {
        var entity = await _productionreportRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _productionreportRep.FakeDeleteAsync(entity);   //假删除
        //await _productionreportRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除生产报工 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除生产报工")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteproductionreportInput> input)
    {
        var exp = Expressionable.Create<productionreport>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _productionreportRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _productionreportRep.FakeDeleteAsync(list);   //假删除
        //return await _productionreportRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataproductionreportInput input)
    {
        var procedurecodeData = await _productionreportRep.Context.Queryable<Processmanage>()
            .InnerJoinIF<productionreport>(input.FromPage, (u, r) => u.Id == r.procedurecode)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.encoding}"
            }).ToListAsync();
        var processnameData = await _productionreportRep.Context.Queryable<Processmanage>()
            .InnerJoinIF<productionreport>(input.FromPage, (u, r) => u.Id == r.processname)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.processname}"
            }).ToListAsync();
        var productcodeData = await _productionreportRep.Context.Queryable<Partnum>()
            .InnerJoinIF<productionreport>(input.FromPage, (u, r) => u.Id == r.productcode)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PartNumCoding}"
            }).ToListAsync();
        var productnameData = await _productionreportRep.Context.Queryable<Partnum>()
            .InnerJoinIF<productionreport>(input.FromPage, (u, r) => u.Id == r.productname)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PartNumName}"
            }).ToListAsync();
        var productspecificationData = await _productionreportRep.Context.Queryable<Partnum>()
            .InnerJoinIF<productionreport>(input.FromPage, (u, r) => u.Id == r.productspecification)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.SpeciFicationNumber}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "procedurecode", procedurecodeData },
            { "processname", processnameData },
            { "productcode", productcodeData },
            { "productname", productnameData },
            { "productspecification", productspecificationData },
        };
    }
    
    /// <summary>
    /// 导出生产报工记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出生产报工记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageproductionreportInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportproductionreportOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "生产报工导出记录");
    }
    
    /// <summary>
    /// 下载生产报工数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载生产报工数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportproductionreportOutput>(), "生产报工导入模板", (_, info) =>
        {
            if (nameof(ExportproductionreportOutput.procedurecodeFkDisplayName) == info.Name) return _productionreportRep.Context.Queryable<Processmanage>().Select(u => $"{u.encoding}").Distinct().ToList();
            if (nameof(ExportproductionreportOutput.processnameFkDisplayName) == info.Name) return _productionreportRep.Context.Queryable<Processmanage>().Select(u => $"{u.processname}").Distinct().ToList();
            if (nameof(ExportproductionreportOutput.productcodeFkDisplayName) == info.Name) return _productionreportRep.Context.Queryable<Partnum>().Select(u => $"{u.PartNumCoding}").Distinct().ToList();
            if (nameof(ExportproductionreportOutput.productnameFkDisplayName) == info.Name) return _productionreportRep.Context.Queryable<Partnum>().Select(u => $"{u.PartNumName}").Distinct().ToList();
            if (nameof(ExportproductionreportOutput.productspecificationFkDisplayName) == info.Name) return _productionreportRep.Context.Queryable<Partnum>().Select(u => $"{u.SpeciFicationNumber}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入生产报工记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入生产报工记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportproductionreportInput, productionreport>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 工序编码
                    var procedurecodeLabelList = pageItems.Where(x => x.procedurecodeFkDisplayName != null).Select(x => x.procedurecodeFkDisplayName).Distinct().ToList();
                    if (procedurecodeLabelList.Any()) {
                        var procedurecodeLinkMap = _productionreportRep.Context.Queryable<Processmanage>().Where(u => procedurecodeLabelList.Contains($"{u.encoding}")).ToList().ToDictionary(u => $"{u.encoding}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.procedurecode = procedurecodeLinkMap.GetValueOrDefault(e.procedurecodeFkDisplayName ?? "");
                            if (e.procedurecode == null) e.Error = "工序编码链接失败";
                        });
                    }
                    // 链接 工序名称
                    var processnameLabelList = pageItems.Where(x => x.processnameFkDisplayName != null).Select(x => x.processnameFkDisplayName).Distinct().ToList();
                    if (processnameLabelList.Any()) {
                        var processnameLinkMap = _productionreportRep.Context.Queryable<Processmanage>().Where(u => processnameLabelList.Contains($"{u.processname}")).ToList().ToDictionary(u => $"{u.processname}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.processname = processnameLinkMap.GetValueOrDefault(e.processnameFkDisplayName ?? "");
                            if (e.processname == null) e.Error = "工序名称链接失败";
                        });
                    }
                    // 链接 产品编码
                    var productcodeLabelList = pageItems.Where(x => x.productcodeFkDisplayName != null).Select(x => x.productcodeFkDisplayName).Distinct().ToList();
                    if (productcodeLabelList.Any()) {
                        var productcodeLinkMap = _productionreportRep.Context.Queryable<Partnum>().Where(u => productcodeLabelList.Contains($"{u.PartNumCoding}")).ToList().ToDictionary(u => $"{u.PartNumCoding}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.productcode = productcodeLinkMap.GetValueOrDefault(e.productcodeFkDisplayName ?? "");
                            if (e.productcode == null) e.Error = "产品编码链接失败";
                        });
                    }
                    // 链接 产品名称
                    var productnameLabelList = pageItems.Where(x => x.productnameFkDisplayName != null).Select(x => x.productnameFkDisplayName).Distinct().ToList();
                    if (productnameLabelList.Any()) {
                        var productnameLinkMap = _productionreportRep.Context.Queryable<Partnum>().Where(u => productnameLabelList.Contains($"{u.PartNumName}")).ToList().ToDictionary(u => $"{u.PartNumName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.productname = productnameLinkMap.GetValueOrDefault(e.productnameFkDisplayName ?? "");
                            if (e.productname == null) e.Error = "产品名称链接失败";
                        });
                    }
                    // 链接 产品规格
                    var productspecificationLabelList = pageItems.Where(x => x.productspecificationFkDisplayName != null).Select(x => x.productspecificationFkDisplayName).Distinct().ToList();
                    if (productspecificationLabelList.Any()) {
                        var productspecificationLinkMap = _productionreportRep.Context.Queryable<Partnum>().Where(u => productspecificationLabelList.Contains($"{u.SpeciFicationNumber}")).ToList().ToDictionary(u => $"{u.SpeciFicationNumber}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.productspecification = productspecificationLinkMap.GetValueOrDefault(e.productspecificationFkDisplayName ?? "");
                            if (e.productspecification == null) e.Error = "产品规格链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<productionreport>>();
                    
                    var storageable = _productionreportRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.reportnumber?.Length > 32, "报工单号长度不能超过32个字符")
                        .SplitError(it => it.Item.workordernumber?.Length > 100, "工单号长度不能超过100个字符")
                        .SplitError(it => it.Item.productionpersonnel?.Length > 32, "生产人员长度不能超过32个字符")
                        .SplitError(it => it.Item.attachments?.Length > 32, "附件长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
